package com.stream.utils.schedule;

import com.alibaba.fastjson.JSON;
import com.stream.model.entity.ScheduleJobEntity;
import com.stream.model.entity.ScheduleJobLogEntity;
import com.stream.service.ScheduleJobLogService;
import com.stream.utils.SpringContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by yebaokang on 2017/6/30.
 */
public class ScheduleJob extends QuartzJobBean {
    private static final Logger logger = LoggerFactory.getLogger(ScheduleJob.class);
    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String jsonJob = context.getMergedJobDataMap().getString(ScheduleJobEntity.JOB_PARAM_KEY);
        ScheduleJobEntity schedulejob = JSON.parseObject(jsonJob, ScheduleJobEntity.class);

        //获取日志
        ScheduleJobLogService logService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");

        ScheduleJobLogEntity scheduleJobLog = new ScheduleJobLogEntity();
        scheduleJobLog.setJobId(schedulejob.getJobId());
        scheduleJobLog.setBeanName(schedulejob.getBeanName());
        scheduleJobLog.setMethodName(schedulejob.getMethodName());
        scheduleJobLog.setParams(schedulejob.getParams());
        scheduleJobLog.setCreateTime(new Date());

        long statrt = System.currentTimeMillis();

        //执行任务
        logger.info("任务准备执行，任务ID:{}",schedulejob.getJobId());
        try {
            ScheduleRunnable task = new ScheduleRunnable(schedulejob.getBeanName(),
                    schedulejob.getMethodName(), schedulejob.getParams());
            Future<?> future = service.submit(task);
            future.get();
            //任务执行时间
            long end = System.currentTimeMillis() - statrt;
            scheduleJobLog.setTimes((int)end);
            //任务状态 0: 成功; 1: 失败
            scheduleJobLog.setStatus(0);

            logger.info("任务执行完毕,任务ID:" + schedulejob.getJobId() + " 总耗时:" + end + "毫秒");
        } catch (Exception e) {
            logger.error("任务执行失败,任务ID:" + schedulejob.getJobId(), e);
            long end = System.currentTimeMillis() - statrt;
            scheduleJobLog.setTimes((int) end);
            //任务状态 0: 成功; 1: 失败
            scheduleJobLog.setStatus(1);
            scheduleJobLog.setError(StringUtils.substring(e.toString(), 0 , 2000));
        } finally {
            logService.save(scheduleJobLog);
        }
    }
}
